﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Net.Sockets;
using System.IO;

namespace TapTapServer
{
    public partial class Form1 : Form
    {
        CsHTTPServer server;
        public Form1()
        {
            InitializeComponent();

        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            server.Stop();
            btnStop.Enabled = false;
            btnRun.Enabled = true;
        }

        private void btnRun_Click(object sender, EventArgs e)
        {
            //backgroundWorker1.RunWorkerAsync();
            server = new MyServer(8080, Settings.Instance.ServerRootPath);
            server.Start();

            server.serverStatusUpdate += new CsHTTPServer.serverStatusUpdateHandler(server_serverStatusUpdate);

            btnStop.Enabled = true;
            btnRun.Enabled = false;
        }

        public delegate void statHandler(object sender, string status);
        void server_serverStatusUpdate(object sender, string status)
        {
            this.BeginInvoke(new statHandler(statusHandler), new object[] { sender, status });
        }
        public void statusHandler(object sender, string status)
        {
            lblStatus.Text = status;
            addToListView(status);
        }

        private void btnOpenServer_Click(object sender, EventArgs e)
        {
            if (folderBrowserServerPath.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                if (!isValidServerDirectory(folderBrowserServerPath.SelectedPath))
                {
                    if (MessageBox.Show("The directory you selected needs to be prepared before the server can run. Do you want to do this now?","Create Server Directory?",MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes) { prepareServerDirectory(folderBrowserServerPath.SelectedPath); }
                    else return;
                }
                Settings.Instance.ServerRootPath = folderBrowserServerPath.SelectedPath;
                gpServer.Enabled = true;
                gpManage.Enabled = true;
            }
        }

        private bool isValidServerDirectory(string dir)
        {
            bool hasTemplates = false;
            bool hasImages = false;
            bool hasStoreIndex = false;
            bool hasTracksFeatures = false;
            bool hasPlistFolder = false;
            bool hasStoreIndex4 = false;

            hasTemplates = (File.Exists(Path.Combine(dir, "default.template")) && File.Exists(Path.Combine(dir, "songInfo.template")));

            string coreSocialPath = Path.Combine(dir, "tapplications", "coresocial", "v1");
            hasStoreIndex = (File.Exists(Path.Combine(coreSocialPath, "store", "default.htm")));
            hasTracksFeatures = (File.Exists(Path.Combine(coreSocialPath, "store", "templates", "TracksFeatured.html")));

            string imagesPath = Path.Combine(coreSocialPath, "common", "images");
            hasImages = (File.Exists(Path.Combine(imagesPath, "chevron.png")) && File.Exists(Path.Combine(imagesPath, "spinner.png")));

            hasPlistFolder = (Directory.Exists(Path.Combine(dir, "tapplications", "ttr", "v3.0")));


            string ttr4Path = Path.Combine(dir, "ttr", "ttr4cmd", "store");
            ttr4Path = Path.Combine(ttr4Path, "featured", "default.htm");
            hasStoreIndex4 = File.Exists(ttr4Path);



            return (hasTemplates && hasImages && hasStoreIndex && hasTracksFeatures && hasPlistFolder && hasStoreIndex4);
        }
        private void prepareServerDirectory(string dir)
        {
            string tapplicationsPath = Path.Combine(dir, "tapplications");
            string coresocialPath = Path.Combine(tapplicationsPath, "coresocial", "v1");
            string imagesPath = Path.Combine(coresocialPath, "common", "images");
            string storePath = Path.Combine(coresocialPath, "store");
            string featuredTrackPath = Path.Combine(storePath, "templates");

            string plistPath = Path.Combine(tapplicationsPath, "ttr", "v3.0");

            string ttr4Path = Path.Combine(dir, "ttr", "ttr4cmd", "store");
            ttr4Path = Path.Combine(ttr4Path, "featured"); //TODO: should be a better way to do this, shouldn't need 2 lines

            Directory.CreateDirectory(tapplicationsPath);
            Directory.CreateDirectory(coresocialPath);
            Directory.CreateDirectory(imagesPath);
            Directory.CreateDirectory(storePath);
            Directory.CreateDirectory(featuredTrackPath);
            Directory.CreateDirectory(plistPath);
            Directory.CreateDirectory(ttr4Path);

            Properties.Resources.ttr3spinner.Save(Path.Combine(imagesPath, "spinner.png"), System.Drawing.Imaging.ImageFormat.Png);
            Properties.Resources.ttr3chevron.Save(Path.Combine(imagesPath, "chevron.png"), System.Drawing.Imaging.ImageFormat.Png);

            File.WriteAllText(Path.Combine(ttr4Path, "default.htm"), Properties.Resources.ttr4TracksFeatured);
            File.WriteAllText(Path.Combine(storePath, "default.htm"), Properties.Resources.ttr3defaultStore);
            File.WriteAllText(Path.Combine(featuredTrackPath, "TracksFeatured.html"), "");

            File.WriteAllText(Path.Combine(plistPath, "index.php"), "");

            File.WriteAllText(Path.Combine(dir, "default.template"), Properties.Resources.defaultTemplate);
            File.WriteAllText(Path.Combine(dir, "songInfo.template"), Properties.Resources.songInfo);


        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (folderBrowserThemes.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                ThemeManager manager = new ThemeManager();
                manager.ProgressChanged += delegate(object managerSender, ProgressChangedEventArgs managerE)
                {
                    lblStatus.Text = (string)managerE.UserState;
                    progressBar1.Value = managerE.ProgressPercentage;
                };
                manager.RunWorkerCompleted += delegate(object managerSender, RunWorkerCompletedEventArgs managerE)
                {
                    gpManage.Enabled = true;
                    progressBar1.Value = 100;
                    lblStatus.Text = "Themes Prepared";
                    addToListView(lblStatus.Text);
                };
                gpManage.Enabled = false;
                addToListView("Processing Themes...");
                manager.processDirectory(folderBrowserThemes.SelectedPath);
            }
        }

        private void btnPrepTracks_Click(object sender, EventArgs e)
        {
            if (folderBrowseTracks.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                TrackManager manager = new TrackManager();
                manager.ProgressChanged += delegate(object managerSender, ProgressChangedEventArgs managerE)
                {
                    lblStatus.Text = (string)managerE.UserState;
                    progressBar1.Value = managerE.ProgressPercentage;
                };
                manager.RunWorkerCompleted += delegate(object managerSender, RunWorkerCompletedEventArgs managerE)
                {
                    gpManage.Enabled = true;
                    progressBar1.Value = 100;
                    lblStatus.Text = "Tracks Prepared";
                    addToListView(lblStatus.Text);
                };
                gpManage.Enabled = false;
                addToListView("Processing Tracks...");
                manager.processDirectory(folderBrowseTracks.SelectedPath);
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (server != null && server.IsAlive)
                server.Stop();
        }

        private void addToListView(string message)
        {
            ListViewItem i = new ListViewItem(DateTime.Now.ToString());
            i.SubItems.Add(message);
            lvLog.Items.Add(i);
            lvLog.EnsureVisible(lvLog.Items.Count - 1);
        }

    }
}
